<template>
  <el-tree-select
    v-model="modelValue"
    v-bind="props.props"
    :data="props.options"
    :filterable="true"
    :multiple="true"
    @change="value => emit('change', { value, label: renderTags(value) })"
  >
    <template #tag>
      <el-tag v-for="tag in renderTags(modelValue ?? [])" type="info" closable @close="handleColse(tag.value)">
        {{ tag.label }}
      </el-tag>
    </template>
  </el-tree-select>
</template>

<script setup lang="ts">
import type { MerakXFormItemTreeSelect, MerakXFormItemOption, MerakXFormItemOptions } from "../index";

import { ElTreeSelect, ElTag } from "element-plus";

const props = defineProps<MerakXFormItemTreeSelect & MerakXFormItemOptions>();

const emit = defineEmits<{
  change: [arg: any];
}>();

const modelValue = defineModel<string[]>("value");

const renderTags = (values: string[]) => {
  const arr: Array<{
    value: string;
    label: string;
  }> = [];
  const queryLabel = (options: MerakXFormItemOption[], value: string) => {
    for (let option of options) {
      if (option.value === value) {
        return [option.label];
      }
      if (!!option.children?.length) {
        const node = queryLabel(option.children, value);
        if (!!node) {
          return [option.label, ...node];
        }
      }
    }
  };
  if (!!props.options) {
    for (let value of values) {
      arr.push({
        value,
        label: queryLabel(props.options, value).join("/")
      });
    }
  }
  return arr;
};

const handleColse = (value: string) => {
  const index = modelValue.value?.findIndex(id => id === value);
  if (typeof index === "number" && index !== -1) {
    const values = [...(modelValue.value ?? [])];
    values.splice(index, 1);
    modelValue.value = values;
    emit("change", { value: values, label: renderTags(values) });
  }
};
</script>
